﻿/* $RCSFile: HelpViewer.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Help/Help/HelpViewer.aspx.cs $
 * $log$
 * Revision 22 2010/08/09 11:10:05  christian.surieux
 *   Added Log comment to all .aspx *.master files
 * Revision 9 2010/08/09 10:09:29  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Collections.Specialized;
using System.Globalization;
using System.Web.Configuration;
using System.Web.Caching;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using AddonNice.Configuration;
using AddonNice.Helpers;
using AddonNice.Diagnostics;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.Help
{
    public partial class HelpViewer : AddonNice.UI.ADNPage
    {
		private const string defaultXslt        = "xsl/viewer.xslt";
		private const string defaultLocation    = "AddonNice/";
		private const string defaultSource      = "AddonNice";
		private const string sourceExtension    = ".xml";

       	

		protected void Page_Load(object sender, System.EventArgs e)
        {
			// set current directory so paths are relative to this page location
			Environment.CurrentDirectory        = Server.MapPath(TemplateSourceDirectory);

			// set localized Page Title
			Title                               = LocalizeHelper.Localize("TAB_TITLE_HELP","AddonNice Help");

			string loc                          = defaultLocation; 
			string src                          = defaultSource;
			string xslt                         = defaultXslt; 
			CultureInfo lang                    = portalSettings.PortalContentLanguage;
			CultureInfo defaultLang             = portalSettings.PortalContentLanguage;
			CultureInfo fallbackLang            = new CultureInfo(WebConfigurationManager.AppSettings["DefaultLanguage"]);
			
            XslCompiledTransform xt; 

			// grab the QueryString
			NameValueCollection qs              = Request.QueryString;
			
			// Read Location
			if ( !string.IsNullOrEmpty(qs["loc"]) )
				loc = qs["loc"]; 

			// Read Source
            if (!string.IsNullOrEmpty(qs["src"]))
                src = qs["src"];
            else
            {
                string loc2 = loc.Trim(new char[] { '/' });
                src = loc2.Substring(loc2.LastIndexOf('/') + 1);
            }
			// Read Culture
			if ( !string.IsNullOrEmpty(qs["lang"]) )
			{
				try
                {
                    lang = new CultureInfo(qs["lang"],false);
                }
				catch{}
			}

			// Read XSLT Stylesheet
			if ( !string.IsNullOrEmpty(qs["xslt"])	&& File.Exists(qs["xslt"])	)
				xslt = qs["xslt"]; 
		
			// create language sequence
			ArrayList langSequence      = new ArrayList(7);
			langSequence.Add(lang);
			if ( !lang.Equals(defaultLang) )
				langSequence.Add(defaultLang);
			if ( !defaultLang.Equals(fallbackLang) )
				langSequence.Add(fallbackLang);
			langSequence.Add(new CultureInfo(string.Empty));

			// create file sequence
			ArrayList fileSequence      = new ArrayList(2);
			fileSequence.Add(AddonNice.Settings.Path.WebPathCombine(loc, src));
			fileSequence.Add(AddonNice.Settings.Path.WebPathCombine(defaultLocation, defaultSource));

			string filePath             = string.Empty;
			bool found                  = false;
			bool asRequested            = true;
			string languageReturned     = string.Empty;
			
			// find a file: format file.lang-name.xml
			foreach ( string _file in fileSequence )
			{
				foreach ( CultureInfo _language in langSequence )
				{
					filePath                = string.Concat(_file,".",_language.Name,sourceExtension);
					filePath                = filePath.Replace("..",".");
					if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine(string.Format("[V]HelpViewver Page_Load filePath: {0}",filePath),PageTraceSwitch.Sw.Info);
					if ( File.Exists(filePath) )
					{
						languageReturned    = _language.Name;
						found               = true;
						break;
					}
					filePath                = string.Concat(_file,".",_language.TwoLetterISOLanguageName,sourceExtension);
					filePath                = filePath.Replace("..",".");
					if (PageTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine(string.Format("[V]HelpViewver Page_Load filePath: {0}",filePath),PageTraceSwitch.Sw.Info);
					if ( File.Exists(filePath) )
					{
						languageReturned    = _language.TwoLetterISOLanguageName;
						found               = true;
						break;
					}
				}
				if ( found )
					break;
				asRequested = false;
			}

			// if we found something to display
			if ( found )
			{
				try
				{
                    /*
                    Dim xdoc As New XmlDocument
                    xdoc.LoadXml(strYourXml)
                    Dim xsdoc As New XslCompiledTransform()
                    xsdoc.Load(xsltFilePath)
                    Dim sw As New StringWriter
                    xsdoc.Transform(xdoc.CreateNavigator(), Nothing, sw)
                    strTransformed = sw.ToString 
                     * */
			        // create the ArgList
			        XsltArgumentList xa         =   new XsltArgumentList();
			        XslHelper xh                =   new XslHelper();
			        xa.AddExtensionObject("urn:AddonNice",xh);
			        AddParam(xa,"LanguageRequested",string.Empty,lang.Name);
			        AddParam(xa,"LanguageReturned",string.Empty,languageReturned);
			        AddParam(xa,"AsRequested",string.Empty,asRequested.ToString());
			        AddParam(xa,"Location",string.Empty,loc);
			        AddParam(xa,"Title",string.Empty,Title);
			        AddParam(xa,"Viewer",string.Empty,Request.Url.AbsolutePath);
			        AddParam(xa,"myRoot",string.Empty,loc.Substring(0,loc.IndexOf("/")));

                    XmlDocument xdoc            =   new XmlDocument();
                    xdoc.Load(filePath);
					xt                          =   new XslCompiledTransform();
					xslt                        =   Server.MapPath(xslt);
					XmlUrlResolver xr           =   new XmlUrlResolver();
					xt.Load(xslt,null,xr);
                    StringWriter sw             =   new StringWriter();
                    xt.Transform(xdoc.CreateNavigator(),xa,sw);
                    myXml.DocumentContent       =   sw.ToString();
				    }		
				catch(Exception ex)
				{
					if (PageTraceSwitch.Sw.TraceError)
                        Trace2.WriteLine(string.Format("[E]HelpViewver Page_Load ex: {0}",ex),PageTraceSwitch.Sw.Info);
					throw ex;
				}
			}
			else
			{
				Literal errorMsg            = new Literal();
				errorMsg.Text               = LocalizeHelper.Localize("HELP_VIEWER_ERROR","Sorry - no help available");
				HtmlGenericControl container = new HtmlGenericControl(StStr.Div);
				container.Attributes.Add("style","padding:3em;font-size:1.2em;text-align:center");
				container.Controls.Add(errorMsg);
				ContentHolder.Controls.Add(container);
			}
        }

        void AddParam(XsltArgumentList xa, string s1, string s2, object o3)
        {
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine(string.Format("[V]HelpViewver AddParam s1: {0}, s2: {1}, o3: {2}",
                new object[]{s1,s2,o3}),PageTraceSwitch.Sw.Info);
            xa.AddParam(s1,s2,o3);
        }

		#region Web Form Designer generated code
        /// <summary>
        /// Raises OnInitEvent
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            Load += new EventHandler(Page_Load);
        }

		#endregion

    }
}
